import {
  getEnergyInfoByPage,
  addEnergyInfo,
  updateEnergyInfo,
  uploadEhsFile,
  getDeIds,
  delEnergyInfo,
  getDictDataByPageAndDictType,
  exportEnergyInfo,
  uploadEnergyInfo
} from '@/services/device/energyInfo';
import { ConfigDataType, Option } from './deviceType';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Col, Form, Input, Modal, Row, Upload, message } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Column } from '@ant-design/charts';
import styles from './style.less';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
//静态数据
const configData = [
  { month: "1", value: 0 },
  { month: "2", value: 0 },
  { month: "3", value: 0 },
  { month: "4", value: 0 },
  { month: "5", value: 0 },
  { month: "6", value: 0 },
  { month: "7", value: 0 },
  { month: "8", value: 0 },
  { month: "9", value: 0 },
  { month: "10", value: 0 },
  { month: "11", value: 0 },
  { month: "12", value: 0 },
];
const EnergyEfficiencyBoard: React.FC<{}> = (props) => {
  useEffect(() => {
    console.log("props:", props);
  }, [])
  useEffect(() => {
    actionRef.current?.reload()
  }, [props.deviceName])
  const [modalVisit, setModalVisit] = useState<boolean>(false);
  const [formTitle, setFormTitle] = useState<string | undefined>(undefined);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [createOrUpdate, setCreateOrUpdate] = useState<boolean>(false);
  const [modalVisit1, setModalVisit1] = useState<boolean>(false);
  const [formTitle1, setFormTitle1] = useState<string | undefined>(undefined);
  const [confirmLoading1, setConfirmLoading1] = useState<boolean>(false);
  const [createOrUpdate1, setCreateOrUpdate1] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [energyInfo, setEnergyInfo] = useState<ConfigDataType[]>(configData);
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const ref = useRef(null);
  const [energyUnit, setEnergyUnit] = useState<Option[] | undefined>(undefined);
  //柱状图配置
  const energyEfficiencyGraphConfig = {
    padding: 'auto',
    forceFit: true,
    data: energyInfo,
    height: 200,
    xField: 'month',
    yField: 'value',
    label: {
      visible: true,
      position: 'middle',
      adjustColor: true,
    },
    meta: {
      month: { alias: '月份', formatter: (v: string) => { return `${v}月` } },
      value: { alias: '计量值' },
    },
  };
  //水电气能效表格数据
  const energyBoardColumn: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: "center",
      width: 80,
    },
    /* {
        title: '唯一标识',
        dataIndex: 'uniqueIdentifier',
        hideInTable: tru e,
      }, */
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      align: 'center',
      sorter: true,
    },
    {
      title: '设备编号',
      dataIndex: 'deviceId',
      align: 'center',
      sorter: true,
    },
    {
      title: '生产区域',
      dataIndex: 'area',
      search: false,
      align: 'center',
      sorter: true,
    },

    {
      title: '能源介质',
      dataIndex: 'energyItem',
      align: 'center',
      sorter: true,

      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '水',
            value: '水',
          },
          {
            label: '电',
            value: '电',
          },
          {
            label: '气',
            value: '气',
          },
        ],
      },
    },
    {
      title: '计量周期',
      dataIndex: 'period',
      align: 'center',
      sorter: true,
    },
    /*     {
        title: '计量刻度',
        dataIndex: 'scale',
       align: 'center',sorter: true, 
      }, */
    {
      title: '计量值',
      search: false,
      dataIndex: 'value',
      align: 'center',
      sorter: true,
    },
    {
      title: '月',
      dataIndex: 'month',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '计量单位',
    //   align: 'center',
    //   sorter: true,
    //   search: false,
    //   dataIndex: 'unit',
    // },

    /* {
        title: '年',
        dataIndex: 'year',
       align: 'center',sorter: true, 
      },
      {
        title: '月',
        dataIndex: 'month',
       align: 'center',sorter: true, 
      },
      {
        title: '日',
        dataIndex: 'day',
       align: 'center',sorter: true, 
      }, */

    // {
    //   title: '创建日期', //表头显示的名称
    //   search: false,

    //   dataIndex: 'createTime',
    //   align: 'center',
    //   sorter: true,
    //   render: (text, record) => <div>{moment(text).format('YYYY-MM-DD')}</div>,
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    //   align: 'center',
    //   sorter: true,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            actionRef.current.reload();
            form.setFieldsValue({
              area: record.area,
              day: record.day,
              deviceId: record.deviceId,
              deviceName: record.deviceName,
              energyItem: record.energyItem,
              month: record.month,
              period: record.period,
              scale: record.scale,
              uniqueIdentifier: record.uniqueIdentifier,
              unit: record.unit,
              updateBy: record.updateBy,
              value: record.value,
              year: record.year,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delEnergyInfo({ id: record.id });
                actionRef.current?.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  //构造图标数据
  const recreateGraphData = (data) => {

    const graphData: ConfigDataType[] = [];
    data.forEach((item: object) => {
      graphData.push({ month: item?.month + '', value: item?.value });
    })
    const modifiedData = configData.map(monthData => {
      // 查找新数据中是否有对应月份的数据 
      const matchingNewData = graphData.find(newMonthData => newMonthData.month === monthData.month);
      // 如果有匹配的新数据，返回新数据，否则返回原始数据
      return matchingNewData ? matchingNewData : monthData;
    });
    console.log(modifiedData);
    setEnergyInfo(modifiedData);
  }
  //表单提交
  const handleSubmit = async (values) => {
    if (formTitle == '新建') {
      setConfirmLoading(true);
      console.log('values---->', values);
      const result = await addEnergyInfo(values);
      console.log('结果', result);
      if (result !== null) {
        console.log("添加成功！");
        message.success('添加成功');
        setConfirmLoading(false);
        setModalVisit(false);
      }
      //编辑
    }
    if (formTitle == '上传水电气能效附件') {
      setConfirmLoading1(true);
      console.log("values---->", form1.getFieldValue(null).file.file);
      const file = form1.getFieldValue(null).file.file
      const formData = new FormData();
      formData.append("file", file);
      const params = {
        file: formData,
      }
      const result = await uploadEnergyInfo(params);
      console.log("updateEnergyInfo---->", result);
      if (result && result.message === '更新成功') {
        message.success('上传成功');
        setConfirmLoading1(false);
        setModalVisit1(false);
        form1.resetFields();
      }
    }
    actionRef.current?.reload();
  };

  //获取单位
  const handleChange = async (value: any) => {
    form.setFieldsValue({ unit: undefined })
    let params = {
      dictTypeId: '',
      pageEntity: {
        current: 1,
        filters: [],
        pageSize: 20,
        sorters: [],
      },
    };
    console.log(`selected ${value}`);
    if (value == '气') {
      params.dictTypeId = '8a827f828aa1786b018aa70ed54303d3';
    } else if (value == '电') {
      params.dictTypeId = '8a827f828aa1786b018aa70eb45403d2';
    } else if (value == '水') {
      params.dictTypeId = '8a827f828aa1786b018aa617a47803c3';
    }
    const temp: any[] = [];
    const resultOrder = await getDictDataByPageAndDictType(params);
    console.log('收到的类型', resultOrder);
    resultOrder?.data?.content.map((item: any) => {
      temp.push({ label: item.keyValue, value: item.keyValue }); //label和value应该都是字符串
    });
    console.log("temp", temp);
    setEnergyUnit(temp);
  };
  const onFilesChange = (file) => {
    console.log("onFilesChange---->", file);
  }
  const handleBeforeUpload = (file) => {
    console.log("handleBeforeUpload---->", file);

    return false;
  }
  return (
    <section className={styles.energyEfficiencyBoardContent}>
      <div className={styles.container}>
        <div className={styles.top}>
          <ProTable
            headerTitle="水电气能效看板"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              labelWidth: 100,
              defaultCollapsed: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="upload"
                icon={<UploadOutlined />}
                onClick={() => {
                  setCreateOrUpdate1(true);
                  setFormTitle('上传水电气能效附件');
                  setModalVisit1(true);
                }}
                type="primary"
              >
                上传水电气能效附件
              </Button>,
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle('新建');
                  form.resetFields();
                  setModalVisit(true);
                }}
                type="primary"
              >
                新建
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              // const res = { ...params }
              const res = { ...params, energyItem: props?.energyItem, deviceName: props?.deviceName };
              const sorters = sortTran(sort);
              const filters = filterTran(res);
              const result = await getEnergyInfoByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              console.log('获得的数据', result);
              recreateGraphData(result.data.content);
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={energyBoardColumn}
            scroll={{ x: 2000, y: 200 }}
          //rowSelection={{ onChange: onSelectChange }}
          />
        </div>
        <div className={styles.bottom}>
          <Column {...energyEfficiencyGraphConfig} />
        </div>
      </div>
      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        // confirmLoading={confirmLoading}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              name="deviceName"
              label="设备名称"
              disabled={createOrUpdate}
              options={props?.deviceOption}
              rules={[{ required: true, message: '请输入设备名称!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="deviceId"
              label="设备编号"
              disabled={createOrUpdate}
              rules={[{ required: true, message: '请选择设备编号!' }]}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              name="energyItem"
              width={350}
              label="能源介质"
              disabled={createOrUpdate}
              onChange={handleChange}
              valueEnum={{
                水: '水',
                电: '电',
                气: '气',
              }}
              rules={[{ required: true, message: '请选择能源截至!' }]}
            // fieldProps={{
            //   autoClearSearchValue: true, //选中后清空搜索框
            //   //使用onChange onBlur
            //   onChange: (value) => {
            //     return value; //必须要return一个值出去 表单项才会展示值在输入框上
            //   },
            // }}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="period"
              label="计量周期"
              disabled
              initialValue={'月'}
              rules={[{ required: true, message: '请输入计量周期!' }]}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="value"
              label="计量值"
              disabled={createOrUpdate}
              rules={[{ required: true, message: '请输入计量值!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="unit"
              label="计量单位"
              placeholder="请选择计量单位"
              disabled={createOrUpdate}
              options={energyUnit}
            />
          </Col>
        </Row>
        <ProFormText
          name="area"
          label="生产区域"
          disabled={createOrUpdate}
          width={350}
          rules={[{ required: true, message: '请输入生产区域!' }]}
        />
      </ModalForm>
      <Modal
        title={formTitle}
        visible={modalVisit1}
        confirmLoading={confirmLoading1}
        onOk={handleSubmit}
        onCancel={() => {
          setModalVisit1(false);
          form1.resetFields();
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form1}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{ category: 'BOM' }}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            <Upload
              file-list="fileList"
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple={true}
              maxCount={1}
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </section>
  );
};
export default EnergyEfficiencyBoard;
